<template>
	<view>
		<uni-file-picker :limit="limit" :file-mediatype="fileType"  @select="select" :title="title" 
			@progress="false" @success="success" @fail="fail" v-model="activeValue">
			<button size="mini" :class="uploadIng?'chooseFile uploadIng':'chooseFile'" >{{uploadIng?'上传中...':'选择文件'}}</button>
			<text class="tips">仅支持MP4格式视频</text>
		</uni-file-picker>
	</view>
</template>

<script>
	import { getAccessToken,getRefreshToken } from '@/utils/auth'
	import config from '@/config'
	export default {
		name: "fileUpload",
		props: {
		    filevalue: {
					type:Array,
					default:[]
				},
		    // 数量限制
		    limit: {
		      type: Number,
		      default: 5,
		    },
		    // 大小限制(MB)
		    fileSize: {
		      type: Number,
		      default: 100,
		    },
				fileType:{
					type: String,
					default:'all'
				},
				title:{
					type: String,
					default: ''
				}
		  },
		data() {
			return {
				activeValue:this.filevalue,
				filePathsList:[],
				uploadIng:false,
				headers: { 
					'Authorization': "Bearer " + getAccessToken(),
					'tenant-id': 1,
				}, // 设置上传的请求头部
			};
		},
		methods: {
			// 获取上传状态
			async select(res) {
				console.log('选择文件：', res)
				let size = res.tempFiles[0].file.size
				if(size > this.fileSize*1024*1024){
					this.activeValue=[]
					uni.showToast({
						title: "文件大小应小于"+this.fileSize+'M',
						icon: "none"
					})
				}else{
					this.uploadIng = true
					await this.uploadFile(res.tempFilePaths);
				}
				
			},
			async uploadFile(tempFilePaths) {
				if (!tempFilePaths.length) return;
				const path = tempFilePaths.pop();
				this.filePathsList.push({
					url: path,
					name: ""
				})
				const [err, {
					data
				}] = await uni.uploadFile({
					url: config.baseUrl + "/admin-api/infra/file/upload", // 请求地址
					filePath: path,
					name: 'file',
					header: this.headers
				});
				let _data = JSON.parse(data);
				if (_data.data == null || _data.data == '') {
					// upload fail
					
					this.filePathsList.pop()
					uni.showToast({
						title: "上传失败",
						icon: "none"
					})
				} else {
					this.uploadIng = false
					uni.showToast({
						title: "视频上传成功",
						icon: "none"
					})
					// upload success
					this.filePathsList[this.filePathsList.length - 1].name = data
					this.activeValue=[]
					this.activeValue.push({ name: _data.data, url: _data.data })
				}
				//this.uploadFile(tempFilePaths);
			},

			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			getValue(){
				return this.activeValue
			},
		}
	}
</script>

<style lang="scss">
 .chooseFile{
	 background-color: rgba(80, 140, 255, 1);
	 color: #fff;
 }
 .uploadIng{
	 background-color: rgba(80, 140, 255, .5);
 }
 .tips{
	 color: #A3A3A3 ;
	 font-size: 12px;
	 padding-left: 5px;
	 position: relative;
	 bottom: 5px;
 }
</style>
